import { DoubleSide, MathUtils, Mesh, MeshBasicMaterial, PlaneGeometry, VideoTexture } from "three";

import { Point } from "../../Engine";
import VideoUtil from "./utils/VideoUtil";

/**
 * 视频融合组件
 */
export default class VideoObject extends Mesh {
    private url = '/examples/resources/video/test.mp4';
    private width: number = 1920;
    private height: number = 1080;
    // private static videoTexture: VideoTexture;
    private static map: Map<string, VideoTexture> = new Map<string, VideoTexture>();

    /**
     * 构造函数
     * @param cfg 
     * @param cfg.position 对象位置
     * @param cfg.url 视频url
     * @param cfg.width 视频宽度（单位为米）
     * @param cfg.height 视频高度（单位为米）
     * @example let videoObject = new GE.VideoObject({
         position: new GE.Point(120.170646, 30.28362, 500),
         url: '/examples/resources/video/test.mp4',
         width: 1920,
         height: 1080
     })
     app.add(videoObject);
     */
    constructor(cfg: { position: Point, url: string, width: number, height: number }) {
        super();
        if (cfg.position) {
            cfg.position = cfg.position.toEPSGWeb();
            this.position.set(cfg.position.x, cfg.position.y, cfg.position.z);
        }
        this.url = cfg.url ? cfg.url : this.url;
        this.width = cfg.width ? cfg.width : this.width;
        this.height = cfg.height ? cfg.height : this.height;

        this.makeGeometry();
        this.makeMaterial();
    }

    private makeGeometry() {
        this.geometry = new PlaneGeometry(this.width, this.height);
    }

    private makeMaterial() {
        let curVideoTexture = VideoObject.map.get(this.url);
        if(!curVideoTexture) {
            let videoUtil = new VideoUtil();
            let videoElement = videoUtil.makeVideoElement(this.url);
            curVideoTexture = new VideoTexture(videoElement);
            VideoObject.map.set(this.url, curVideoTexture);
        }

        this.material = new MeshBasicMaterial({
            map: curVideoTexture, //new VideoTexture(this.videoElement),
            side: DoubleSide
        });
    }



    public dispose() {

    }
}